package net.kleinhenz.droidshop;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import net.kleinhenz.droidshop.model.Product;
import net.kleinhenz.droidshop.xml.DroidShopXMLException;
import net.kleinhenz.droidshop.xml.DroidShopXMLHandler;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class ProductInfoThread extends Thread
{
	public static final int OK = 0;
	public static final int ERROR_PARSING = -1;
	public static final int ERROR_RETRIEVING = -2;
	
	private Context context = null;
	private Mode mode = null;
	private String keywords = null;
	private String locale = null;
	private Handler handler = null;
	private List<Product> productList = null;
	
	public enum Mode { LOOKUP, SEARCH }
	
	public ProductInfoThread(Context context, Mode mode, String keywords, String locale, Handler handler) 
	{
		super();
		this.mode = mode;
		this.context = context;
		this.keywords = keywords;
		this.locale = locale;
		this.handler = handler;
	}
	
	public List<Product> getResult()
	{
		return this.productList;
	}
	
	@Override
	public void run()
	{
		DroidShopXMLHandler xmlHandler = new DroidShopXMLHandler();
		try 
		{
			Log.i("DroidShop", "Getting results for: " + keywords);
			
			// current api is /{lookup|search}/{locale}/{client}/{ip}/{ean}
			String url = null;
			if (this.mode==Mode.LOOKUP)
				url = context.getResources().getString(R.string.lookup_url) + locale.toUpperCase() + "/" + DroidShop.getClient() + "/" + DroidShop.getIPAddress() + "/" + keywords;
			else
				url = context.getResources().getString(R.string.search_url) + locale.toUpperCase() + "/" + DroidShop.getClient() + "/" + DroidShop.getIPAddress() + "/" + keywords;
				
			productList = xmlHandler.readDroidShopXML(new URL(url));
			handler.sendEmptyMessage(OK);
		} 
		catch (DroidShopXMLException e) 
		{
			Log.e("DroidShop", "Error while parsing server result XML: " + e.getMessage());			
			handler.sendEmptyMessage(ERROR_PARSING);
		} 
		catch (IOException e) 
		{
			Log.e("DroidShop", "Error while retrieving server result XML: " + e.getMessage());
			handler.sendEmptyMessage(ERROR_RETRIEVING);
		}		
	}
}
